package com.xhsj.user.timer;

import com.google.common.collect.Maps;
import com.xhsj.user.event.event.MessageEvent;
import com.xhsj.user.hr.process.hrBecomeRegular.service.TbHrApprovalBecomeRegularApplyService;
import com.xhsj.user.hr.process.hrChangeSalary.entity.TbHrApprovalChangeSalary;
import com.xhsj.user.hr.process.hrChangeSalary.service.TbHrApprovalChangeSalaryService;
import com.xhsj.user.hr.process.hrTransferJob.service.TbHrApprovalTransferJobService;
import com.xhsj.user.hr.process.message.entity.TbProjectMessage;
import com.xhsj.user.hr.process.message.service.TbProjectMessageService;
import com.xhsj.user.hr.process.processDefinition.query.HrMessageQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.pms.patent.query.SendMessagePatentQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.entity.TbHrApprovalDimissionApply;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.hr.system.service.TbHrApprovalDimissionApplyService;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: liuqinghua
 * @Description:定时器 定期生效
 * @Data:2020/9/18
 */
@Component
public class TbHrApprovalTimer {
    @Autowired
    private TbHrApprovalTransferJobService tbHrApprovalTransferJobService;

    @Autowired
    private TbHrApprovalChangeSalaryService tbHrApprovalChangeSalaryService;

    @Autowired
    private TbHrApprovalBecomeRegularApplyService tbHrApprovalBecomeRegularApplyService;

    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private TbHrApprovalDimissionApplyService tbHrApprovalDimissionApplyService;

    @Autowired
    private TbProjectMessageService tbProjectMessageService;

    @Value("${spring.profiles.active}")
    private String profiles;


    /**
     * 调岗定时器
     * @throws Exception
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void excute() throws Exception {
        tbHrApprovalTransferJobService.approvalTransferJobEffective();
    }

    /**
     * 调薪定时器
     * @throws Exception
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void excuteChangeSalary() throws Exception {
        tbHrApprovalChangeSalaryService.approvalChangeSalaryEffective();
    }

    /**
     * 转正定时器
     * @throws Exception
     */
    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(cron = "*/30 * * * * ?")
    public void excuteBecomeRegular() throws Exception {
        tbHrApprovalBecomeRegularApplyService.approvalBecomeRegularEffective();
    }

    /**
     * 到达离职时间后禁用用户登录 -每天下午6点   凌晨1点执行0 0 1 * * ?
     * @author 苏小林
     * @date 2020/11/2 16:54
     */
    @Scheduled(cron = "0 0 18 * * ?")
    public void execDisableUser() {

        LocalDate now = LocalDate.now();
        List<Long> list = tbHrApprovalDimissionApplyService.findListByLeaveDate(now);
        for (Long id : list) {
            TbGlobalUser tbGlobalUser = new TbGlobalUser();
            tbGlobalUser.setUserId(id);
            tbGlobalUser.setStatus(1);
            tbGlobalUserService.updateById(tbGlobalUser);
        }
    }

    /**
     * 首页hr系统管理消息待办发消息
     */
    @Scheduled(cron = "0 15 9 * * ?")
    public void sendMessageNeedDeal () throws Exception {
        // 通过权限获取用户  tb:global:hr:commission:num  接收者
        List<Long> receiveUserIds = tbGlobalUserService.getUserIdByPrem("tb:global:hr:commission:num");

        if (receiveUserIds.size()>0) {
        List<HrMessageQuery> hrMessageCommissionNotPage = tbGlobalApprovalTaskService.getHrMessageCommissionNotPage();
        for (HrMessageQuery hrMessageCommission : hrMessageCommissionNotPage) {
            String fullName = hrMessageCommission.getFullName();
            Long dictId = hrMessageCommission.getDictId();
            // 消息发送
            Map<String, Object> messageMap = Maps.newHashMap();
            messageMap.put("projectId",5);
            messageMap.put("dataId", 0); // 业务id
            messageMap.put("sender", 0); // 发送者
            messageMap.put("userIds", receiveUserIds);

                if (dictId == 1 && fullName != null) {
                    messageMap.put("title", "用户"+fullName+"合同即将到期-代办统计-hr系统管理"); // 标题
                }
                else if (dictId == 2 && fullName != null){
                    messageMap.put("title", "用户"+fullName+"即将转正-代办统计-hr系统管理"); // 标题
                }
                applicationContext.publishEvent(new MessageEvent(this, messageMap));


            }
        }
    }



    /**
     *  定时器 每天下午5点半发一次
     * @throws Exception
     */
    @Scheduled(cron = "0 30 17 * * ?")
    public void excutePatent() {
        List<TbProjectMessage> sendMessageList = tbProjectMessageService.getSendMessageList();

        if (sendMessageList.size() != 0) {
            List<SendMessagePatentQuery> recipientList = new ArrayList<>();
            for (TbProjectMessage sendMessage: sendMessageList) {
                SendMessagePatentQuery query = new SendMessagePatentQuery();
                query.setFullName(sendMessage.getFullName());
                query.setRecipient(sendMessage.getRecipient());
                recipientList.add(query);
                sendMessage.setStatus(1);
            }

            List<String> recipients = recipientList.stream().map(s -> s.getRecipient()).collect(Collectors.toList());
            List<TbGlobalUser> byId = tbGlobalUserService.getByIds(recipients);
            for (TbGlobalUser user:byId) {
                if(!StringUtils.isBlank(user.getPhoneNumber()) && !"290".equals(user.getUserId())) {
                    List<String> fullNames = recipientList.stream().filter(q -> q.getRecipient().equals(String.valueOf(user.getUserId()))).map(l -> l.getFullName()).distinct().collect(Collectors.toList());
                    String fullName = org.apache.commons.lang.StringUtils.join(fullNames, ",");
                    CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
                        if ("pro".equals(profiles)) {
                            tbProjectMessageService.sendMessage(user.getPhoneNumber(), "专利管理", 1,fullName);
                        }else{
                            System.err.println("消息发送");
                            tbProjectMessageService.sendMessage("188011353871","专利管理",1,fullName);
                        }
                    });
                }
            }

            tbProjectMessageService.updateBatchById(sendMessageList);
        }

    }

    // 定时


}
